#!/bin/bash

# Copyright (c) 2023 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# build TA and sign TA.
# build and run tests

set -e
source ./config.sh

project_dir=$(realpath $(dirname $0))
ta_root=${TA_ROOT_DIR}

clean() {
	rm -fr build
	rm -fr output
}

build_ta() {
	clean

	cmake -B build/aarch64_release \
		-S $project_dir \
		-DCMAKE_TOOLCHAIN_FILE="$ta_root/ta_common/cmake/aarch64_toolchain.cmake" \
		-DCMAKE_EXPORT_COMPILE_COMMANDS=1 \
		-G Ninja
	cmake --build build/aarch64_release --target se_base_services_project_ta

	cmake -B build/aarch64_factory \
		-S $project_dir \
		-DCMAKE_TOOLCHAIN_FILE="$ta_root/ta_common/cmake/aarch64_toolchain.cmake" \
		-DCMAKE_EXPORT_COMPILE_COMMANDS=1 \
		-DENABLE_FACTORY=1 \
		-G Ninja
	cmake --build build/aarch64_factory --target se_base_services_project_ta
}

build_test() {
	report_dir=$project_dir/build/unit_test_report

	# build
	cmake -B build \
		-S $project_dir \
		-DCMAKE_TOOLCHAIN_FILE="$project_dir/cmake/x86_64_toolchain.cmake" \
		-DCMAKE_EXPORT_COMPILE_COMMANDS=1 \
		-DENABLE_TESTING=1 \
		-DENABLE_FACTORY=1 \
		-DENABLE_COVERAGE=1 \
		-G Ninja
	cmake --build build

	# test
	GTEST_OUTPUT=xml:$report_dir/xml/ ctest --test-dir build

	# coverage report
	pushd build
	rm -rf _deps
	rm -rf test
	rm -rf se_base_services_fwk/test/
	lcov --gcov-tool $project_dir/gcov_tools --rc lcov_branch_coverage=1 -c -d . -o coverage.total
	genhtml -s --rc genhtml_branch_coverage=1 coverage.total -o $report_dir/cov
	popd

}

build_fuzz() {
	cmake -B build -S $project_dir \
		-DCMAKE_TOOLCHAIN_FILE="$project_dir/cmake/x86_64_toolchain.cmake" \
		-DCMAKE_EXPORT_COMPILE_COMMANDS=1 \
		-DENABLE_TESTING=1 \
		-DENABLE_FACTORY=1 \
		-DENABLE_FUZZ=1 \
		-G Ninja
	cmake --build build --target fuzz

	pushd build/test
	if [ "$#" -eq 0 ]; then
		./fuzztest/fuzz/fuzz -runs=100000000 -fork=62 -ignore_crashes=1 2>&1 | tee fuzz_result.log || true
	else
		./fuzztest/fuzz/fuzz $* 2>&1 | tee fuzz_result.log || true
	fi
	popd

	pushd build
	rm -rf se_base_services_fwk/test/unittest/dependencies/CMakeFiles/securec.dir
	lcov --gcov-tool $project_dir/gcov_tools --rc lcov_branch_coverage=1 -c -d code -d se_base_services_fwk -o fuzz_test
	genhtml -s --rc genhtml_branch_coverage=1 fuzz_test -o fuzz_test_reprot
	popd
}

case "$1" in
	"clean") clean ;;
	"fuzz") shift && build_fuzz $* ;;
	"ta") build_ta ;;
	"test") build_test ;;
	*) build_ta ;;
esac
